<?php

class LotController extends \BaseController {

    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index()
    {
        $lots = Lot::whereHas('group', function($q) {
                $q->where('group_id', '=', Auth::user()->group_id);
            })->get();
        
        return View::make('crud.index', array (
            'objects'=>$lots, 
            'title'=>'my inventory',
            'columns'=>Lot::indexColumns(),
            'table'=>'lots'
        ));
    }
    
    /**
     * Show the form for creating a new resource.
     *
     * @return Response
     */
    public function create()
    {
        $item_categories = ItemCategory::whereHas('group', function($q) {
                $q->where('group_id', '=', Auth::user()->group_id);
            })->get()->sortBy('name')->lists('name', 'id');

        if (sizeof($item_categories)) {            
            foreach ($item_categories as $id=>$val) {
                $first_cat_id = $id;
                break;
            }
        } else {
            $first_cat_id = 0;
        }

        $item_types = ItemType::whereHas('group', function($q) {
                $q->where('group_id', '=', Auth::user()->group_id);
            })
            ->where('item_category_id', '=', $first_cat_id)
            ->get()
            ->sortBy('name')
            ->lists('name', 'id');
        
        $containers = Container::whereHas('group', function($q) {
                $q->where('group_id', '=', Auth::user()->group_id);
            })->get()->sortBy('name')->lists('name', 'id');
        
        return View::make('check_in')->with(array (
            'title'=> 'check in',
            'item_categories'=>$item_categories,
            'item_types'=>$item_types,
            'containers'=>$containers,
        ));
    }
    
    /**
     * Store a newly created resource in storage.
     *
     * @return Response
     */
    public function store()
    {
        $validator = Validator::make(
            Input::all(),
            array (
                'item_type_id' => 'required|ingroup:ItemType',
                'container_id' => 'required|ingroup:Container',
                'qty' => 'required|numeric|min:1|max:200',
                'product_date' => 'date|after:1950-01-01',
                'pounds_per_item' => 'numeric'
            )
        );
        
        if ($validator->fails()) {
            return Redirect::to('lots/create')->withErrors($validator)->withInput();       
        } else {
            $group = Group::find(Auth::user()->group_id);
            $type = ItemType::find(Input::get('item_type_id'));
            $container = Container::find(Input::get('container_id'));
            
            $lot = new Lot;
            $lot->pounds_per_item = Input::get('pounds_per_item');
            $lot->product_date = date('Y-m-d', strtotime(Input::get('product_date')));
            $lot->group()->associate($group);
            $lot->container()->associate($container);
            $lot->itemType()->associate($type);
            $lot->save();
            
            $num = Item::max('item_number');
            for ($i=0; $i<Input::get('qty'); ++$i) {
                $item = new Item;
                $item->group_id = $group->id;
                $item->lot_id = $lot->id;
                $item->item_number = $num + $i + 1;
                $item->save();
            }
            
            Session::flash('message', 'Check in successful');
            return View::make('check_in_success')->with(                
                array (
                    'title' => 'success',
                    'start_num'=>$lot->items->min('item_number'),
                    'end_num'  =>$lot->items->max('item_number')
                )
            );
            
        }
    }
    
    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return Response
     */
    public function show($id)
    {
        $object = Lot::find($id);
        $this->checkModel($object);
        
        
        // are there items using this type?
        $allow_delete = true; //false; //!(Item::where('item_type_id', '=', $id)->count());
        
        // show the view and pass the object to it
        return View::make('crud.show')
            ->with(array ('object'=>$object, 'title'=>$object->showTitle(), 'allow_delete'=>$allow_delete));
        
    }
    
    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return Response
     */
    public function edit($id)
    {
        $object = Lot::find($id);
        $this->checkModel($object);
        
        return View::make('crud.form')->with(array (
            'title'=>'edit '.$object->name, 
            'object' => $object,
            'table' => 'lots',
            'fields'=>Lot::editFields($object),
        ));
    }
    
    /**
     * Update the specified resource in storage.
     *
     * @param  int  $id
     * @return Response
     */
    public function update($id)
    {
        $lot = Lot::find($id);
        $this->checkModel($lot);

        $validator = Validator::make(
            Input::all(),
            array (
                'item_type_id' => 'required|ingroup:ItemType',
                'container_id' => 'required|ingroup:Container',
                'product_date' => 'date|after:1950-01-01',
                'pounds_per_item' => 'numeric'
            )
        );
        
        if ($validator->fails()) {
            return Redirect::to('lots/' . $id)->withErrors($validator)->withInput();       
        } else {
            $type = ItemType::find(Input::get('item_type_id'));
            $container = Container::find(Input::get('container_id'));
            
            $lot->pounds_per_item = Input::get('pounds_per_item');
            $lot->product_date = date('Y-m-d', strtotime(Input::get('product_date')));
            $lot->container()->associate($container);
            $lot->itemType()->associate($type);
            $lot->save();
        }

        Session::flash('message', 'Successfully updated item ' . $lot->id);

        return Redirect::to('/lots');
    }
    
    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return Response
     */
    public function destroy($id)
    {
        $lot = Lot::find($id);
        if ($lot) {
            $this->checkModel($lot);

            //$lot->items->destroy();
            Lot::destroy($id);
            foreach ($lot->items as $item) {
                Item::destroy($item->id);
            }
        }

        return Redirect::to('/lots');        
    }
    
}